import { useState, memo, useCallback } from "react";
import { ButtonChangePorps, ButtonItem } from "../../type/button";
import Buttons from "../../components/button";
import { ColumnsType, Key } from "antd/es/table/interface";
import styles from "./index.module.css";
import { Button, Input, Space, Table } from "antd";
import _ from "lodash";
import ModalFrom from "../../components/modalForm";
import { useFetchTableList } from "../../hooks/use-fetch-table-list";
import { adminCreate, adminEdit, deladminTable, getUserAdminTable } from "../../api/admin";
import { BaseTableColumns } from "../../type/active";
import { AdminTableColums } from "../../type/admin";
import { useCreate } from "../../hooks/use-table-create";
import { useDeleteTable } from "../../hooks/use-delete-table";

function Index() {
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  const [open, setOpen] = useState<boolean>(false);
  const [modalTitle, setModalTitle] = useState<string>("新增");
  const [editData, setEditData] = useState<AdminTableColums>({});
  const [detailid, setDetailid] = useState<number>(0);
  const { setParams } = useCreate({
    API: adminCreate,
  });
  const { setDeleteProps, deleteTable } = useDeleteTable({
    API: deladminTable,
    title: "就是要删除你呢",
    success: () => {
      setSelectedRowKeys([]);
      // 根据业务逻辑 删除成功以后要重置分页参数为1
      setFilterParams({ ...filterParams, page: 1 });
    },
  });
  const { dataSource, total, filterParams, setFilterParams } =
    useFetchTableList({
      API: getUserAdminTable,
    });
  // tab 按钮点击
  const onButtonChange = (keys: ButtonChangePorps) => {
    const { value } = keys;
    if (value === "新增") {
      showModal();
    }else  if (value === "删除") {
      const changeDeleteProps = selectedRowKeys.map((ite: any) =>
        ite.toString()
      );
      setDeleteProps(changeDeleteProps);
    } 
  };
  // 输入框检索
  const inputSearch = useCallback(
    _.debounce((e: any) => {
      setFilterParams({
        ...filterParams,
        searchValue: e.target.value,
        page: 1,
      } as any);
    }, 300),
    []
  );
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const closeModal = () => {
    setOpen(false);
    setDetailid(0);
  };
  // 弹框点击部分
  const showModal = (title: string = "") => {
    setOpen(true);
    const modalTitle = title ? title : "新增";
    setModalTitle(modalTitle);
  };
  const onOk = async (val: AdminTableColums) => {
    setParams(val);
  };
  // 编辑
  const handleClickEdit = async (item: AdminTableColums) => {
    showModal("编辑");
    if (item.id) {
      const res: any = await adminEdit({ id: item.id });
      setDetailid(item.id);
      setEditData(res.dataSource);
    }
  };
  const columns: ColumnsType<BaseTableColumns> = [
    {
      title: "昵称",
      dataIndex: "name",
      key: "id",
      width: 200,
    },

    {
      title: "用户名",
      dataIndex: "userName",
      width: 120,
      key: "id",
    },
    {
      title: "密码",
      dataIndex: "passWorld",
      width: 100,
      key: "id",
    },
    {
      title: "备注",
      dataIndex: "remarks",
      width: 100,
      key: "id",
    },
    {
      title: "操作",
      key: "id",
      render: (text, item) => {
        return (
          <Space>
            <Button type="primary" onClick={() => handleClickEdit(item)}>
              编辑
            </Button>
            <Button danger  onClick={() => {
                deleteTable([item.id.toString()]);
              }}>删除</Button>
          </Space>
        );
      },
    },
  ];
  const buttonList: ButtonItem[] = [
    {
      type: "default",
      label: "刷新",

      disabled: false,
      danger: false,
    },
    {
      type: "primary",
      label: "新增",
      danger: false,
      disabled: false,
    },

    {
      type: "default",
      danger: true,
      disabled: selectedRowKeys.length === 0,
      label: "删除",
    },
  ];
  const FormFiledList = [
    {
      type: "Input",
      name: "name",
      label: "昵称",
      required: true,
      message: "请输入昵称",
    },
    {
      type: "Input",
      name: "userName",
      label: "用户名",
    },
    {
      type: "Input",
      name: "passWorld",
      label: "密码",
    },
    {
      type: "Input",
      name: "remarks",
      label: "备注",
    },
  ];
  return (
    <div>
      <div className={styles.admincontainer}>
        <Buttons
          buttonConfig={buttonList}
          onChange={(buttonChangeProp: ButtonChangePorps) =>
            onButtonChange(buttonChangeProp)
          }
        />
        <Input
          placeholder="请输入用户名"
          className={styles.activeInput}
          onChange={inputSearch}
        />
      </div>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        rowKey={(record) => record.id}
        style={{ marginTop: "20px" }}
        pagination={{
          total,
          pageSize: filterParams.pageSize,
          current: filterParams.page,
          onChange: (page) => {
            setFilterParams({
              ...filterParams,
              page,
            });
          },
        }}
      />
      <ModalFrom
        close={closeModal}
        editData={editData}
        onOk={(val) => onOk(val)}
        FormFiledList={FormFiledList}
        detailid={detailid}
        modalTitle={modalTitle}
        openModalFlag={open}
      />
    </div>
  );
}
export default memo(Index);
